package review.system.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import review.config.Constants;
import review.dao.MenuDAO;
import review.entity.Menu;


@Service
@Transactional
public class MenuServiceImpl implements MenuService { //
	
	@Autowired
	private MenuDAO menusDAO;
	@Autowired
	private UserService userService;
	
	public void addMenuItem(Menu item) {
		if (!StringUtils.hasText(item.getName())) {
			throw new RuntimeException("请输入菜单项名称");
		}
		if(!StringUtils.hasText( item.getRoles())) {
			item.setRoles(Constants.ROLE_ADMIN);
		}		
		menusDAO.save(item);
	}
	
	public List<Menu> findAll() {
		List<Menu> menus = new ArrayList<>();
		Set<Menu> set = new HashSet<>();
		List<String> roles = userService.findRolesByLoginUser();
		for (String role : roles) {
			List<Menu> menuList = menusDAO.findByRole(role);
			set.addAll(menuList);
		}
		menus.addAll(set);
		Collections.sort(menus);
		
		return menus;
	}
	
	public JSONObject transformJSON(List<Menu> menus) {
		JSONArray rootArray = new JSONArray();
		for (Menu item : menus) {
			if (item.getLevel().intValue() == 1) {
				JSONObject obj = getMenuJSON(item);
				obj.put("list", new JSONArray());
				rootArray.add(obj);
			}
		}
		for (Menu item : menus) {
			if (item.getLevel().intValue() == 2) {
				JSONObject obj = findParent(item.getParent(), rootArray);
				if (obj == null) {
					continue;
				}
				((JSONArray)obj.get("list")).add(getMenuJSON(item));
			}			
		}
		JSONObject object = new JSONObject();
		object.put(Constants.DATA, rootArray);
		object.put(Constants.SUCCESS, true);
		object.put(Constants.CODE, 0);
		object.put(Constants.MSG, "");
		return object;
	}
	
	private JSONObject findParent(Integer pid, JSONArray rootArray) {
		if ( pid == null ) {
			return null;
		}
		for (Object object : rootArray) {
			JSONObject obj = (JSONObject)object;
			if (obj.getInteger(Constants.ID) == pid.intValue()) {
				return obj;
			}
		}
		return null;
	}
	
	private JSONObject getMenuJSON(Menu menus) {
		JSONObject object = new JSONObject();
		object.put(Constants.JSON_PATH, menus.getHref());
		
		object.put(Constants.JSON_META_TITLE, menus.getName());
		
		object.put(Constants.JSON_NAME, "page" + menus.getId());
		
		object.put(Constants.JSON_META_ICON, menus.getIconClass());
	
		object.put(Constants.ID, menus.getId());

		object.put(Constants.JSON_PID, menus.getParent());
		
		return object;
	}
		
}
